package com.cskaoyan.service.wx_user;

import com.cskaoyan.bean.user.User;
import com.cskaoyan.bean.user.UserExample;
import com.cskaoyan.bean.wx_user.bo.WxRegisteredBo;
import com.cskaoyan.bean.wx_user.bo.WxResetBo;
import com.cskaoyan.bean.wx_user.exception.AddUserException;
import com.cskaoyan.mapper.user.UserMapper;
import com.cskaoyan.utils.EncryptUtil;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author liXiaoFei
 * @date 2021/10/22 9:29
 */
@Service
public class WxUserServiceImpl implements WxUserService {

    @Autowired
    UserMapper userMapper;
    @Override
    public User addUser(WxRegisteredBo wxRegisteredBo) throws AddUserException {
        User user = new User();
        user.setUsername(wxRegisteredBo.getUsername());
        user.setPassword(EncryptUtil.MD5(wxRegisteredBo.getPassword()));
        user.setMobile(wxRegisteredBo.getMobile());
        user.setWeixinOpenid(wxRegisteredBo.getWxCode());
        user.setAddTime(new Date(System.currentTimeMillis()));
        user.setUpdateTime(new Date(System.currentTimeMillis()));
        int rows = userMapper.insertSelective(user);
        if (rows == 0) throw new AddUserException();
        return user;
    }

    @Override
    public void updateUserInfoByLogin(User user, String addr) {
        user.setLastLoginIp(addr);
        user.setLastLoginTime(new Date(System.currentTimeMillis()));
        int code = userMapper.updateByPrimaryKeySelective(user);
        if (code == 0) throw new UnknownAccountException();
    }

    @Override
    public User UpdateUserPassword(WxResetBo wxResetBo) {
        User user = new User();
        user.setPassword(wxResetBo.getPassword());
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andMobileEqualTo(wxResetBo.getMobile());
        userMapper.updateByExampleSelective(user, example);

        List<User> users = userMapper.selectByExample(example);

        return users.get(0);
    }
}
